﻿using OnlineLearningSystem.IRepository;
using OnlineLearningSystem.Model;
using OnlineLearningSystem.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Linq;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace OnlineLearningSystem.Controllers
{
    /// <summary>
    /// 用户管理
    /// </summary>
    public class UsersController : BaseController
    {
        private AppDbContext _context;
        private readonly IConfiguration _configuration;
        public UsersController(IUserRepository userService, ICourseRepository courseService,
            IBatchRepository batchService, ILearningSituationRepository learningSituationService,
            ITestRepository testService, ITopicRepository topicService, IConfiguration configuration)
            : base(userService,courseService, batchService, learningSituationService, testService, topicService)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Login(string account, string password)
        {

            int code = 0;
            string message = "";
            User data = new User();
            var user = new Model.User();
            try
            {
                user = _userService.Get(account);
                if (user != null && user.password == password)
                {
                    if (user.state == 1)
                    {
                        code = 401;
                        message = "无权限！";
                    }
                    else
                    {
                        ////下发令牌
                        //var token = JWTSetUp.GenerateJWT(_configuration["JWT:SecurityKey"], _configuration["JWT:Issuer"], _configuration["JWT:Audience"]);
                        //user.token = token;
                        _userService.Update(user);
                        code = 200;
                        message = "登录成功！";
                        data = user;

                        return new JsonResult(new { code, message, data });
                    }
                }
                else
                {
                    code = 500;
                    message = "密码错误或账号不存在！";
                }
            }
            catch
            {
                code = 500;
                message = "系统错误！";
            }
            return new JsonResult(new { code, message });
        }

        /// <summary>
        /// 根据条件查询用户
        /// </summary>
        /// <param name="user">userName、userAge、userSex（0,1）、userTelphone、role（0,1,2）、account、state（0,1）</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetAllUsers(dynamic user)
        {
            int code = 0;
            string message = "";
            List<User> data = new List<User>();
            try
            {
                data = _userService.GetAll(user);
                code = 200;
                message = "查询成功！";
            }
            catch
            {
                code = 500;
                message = "查询失败！";
                return new JsonResult(new { code, message });
            };
            return new JsonResult(new { code, message, data });
        }

        /// <summary>
        ///用户禁用
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpGet]
        public JsonResult BanUsers(int id)
        {
            int code = 0;
            string message = "";
            try
            {
                User user = _userService.Get(b => b.ID == id);
                user.state = user.state == 1 ? 0 : 1;
                _userService.Update(user);
                code = 200;
                message = "成功！";
            }
            catch
            {
                code = 500;
                message = "失败！";
                return new JsonResult(new { code, message });
            };
            return new JsonResult(new { code, message });
        }


        /// <summary>
        ///用户信息修改
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpPost]
        public JsonResult EditUsers(User user)
        {
            int code = 0;
            string message = "";
            User data = new User();
            try
            {
                User users = _userService.Get(b => b.userTelphone == user.userTelphone);

                if (users==null)
                {
                    User newuser = _userService.Get(b => b.ID == user.ID);
                    newuser.account = user.userTelphone;
                    newuser.userTelphone = user.userTelphone;
                    newuser.userName = user.userName;
                    newuser.userSex = user.userSex;
                    newuser.userAge = user.userAge;
                    _userService.Update(newuser);
                    data = newuser;
                    code = 200;
                    message = "成功！";
                }
                else
                {
                    code = 500;
                    message = "电话号码已存在！";
                }
               
            }
            catch
            {
                code = 500;
                message = "失败！";
                return new JsonResult(new { code, message });
            };
            return new JsonResult(new { code, message, data });
        }


        /// <summary>
        ///用户修改密码
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpGet]
        public JsonResult EditPassword(string oldPassword, string newPaswword, int id)
        {
            int code = 0;
            string message = "";
            try
            {
                User user = _userService.Get(b => b.ID == id);

                if (user.password == oldPassword)
                {
                    user.password = newPaswword;
                    _userService.Update(user);
                    code = 200;
                    message = "修改成功！";
                }
                else
                {
                    code = 500;
                    message = "原密码错误失败！";
                }
            }
            catch
            {
                code = 500;
                message = "失败！";
                return new JsonResult(new { code, message });
            };
            return new JsonResult(new { code, message });
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult AddUsers(User user)
        {

            int code = 0;
            string message = "";
            try
            {
                code = 200;
                message = "提交成功！";
                User a = _userService.Get(user.account);
                if (_userService.Get(user.account) != null)
                {
                    code = 500;
                    message = "电话号码已存在！";
                }
                else
                {
                    _userService.Create(user);
                }
            }
            catch
            {
                code = 500;
                message = "提交失败！";
            }
            return new JsonResult(new { code, message });
        }
    }
}
